package offer_test_40;

import struct.BinaryTreeNode;
import struct.LinkedList;

import java.util.Queue;

//从上往下打印二叉树的每个结点，同一层的结点按照从左到右的顺序打印。 (层次遍历)
public class three_PrintTreeInLayer {
	public static void main(String[] args) {
		BinaryTreeNode root1 = new BinaryTreeNode();
		BinaryTreeNode node1 = new BinaryTreeNode();
		BinaryTreeNode node2 = new BinaryTreeNode();
		BinaryTreeNode node3 = new BinaryTreeNode();
		BinaryTreeNode node4 = new BinaryTreeNode();
		BinaryTreeNode node5 = new BinaryTreeNode();
		BinaryTreeNode node6 = new BinaryTreeNode();
		root1.leftNode = node1;
		root1.rightNode = node2;
		node1.leftNode = node3;
		node1.rightNode = node4;
		node4.leftNode = node5;
		node4.rightNode = node6;
		root1.value = 8;
		node1.value = 8;
		node2.value = 7;
		node3.value = 9;
		node4.value = 2;
		node5.value = 4;
		node6.value = 7;
		printtree(root1);
	}

	public static void printtree(BinaryTreeNode root) {
		BinaryTreeNode node = root;
		Queue<BinaryTreeNode> layerlist = new java.util.LinkedList();
		if (node != null) {
			layerlist.add(node);
		}
		printinlayer(layerlist);
	}

	public static void printinlayer(Queue<BinaryTreeNode> list) {
		if (!list.isEmpty()) {
			Queue<BinaryTreeNode> temp=new java.util.LinkedList();
			for (BinaryTreeNode b : list) {
				System.out.print(b.value+" ");
				if(b.leftNode!=null)temp.add(b.leftNode);
				if(b.rightNode!=null)temp.add(b.rightNode);
			}
			printinlayer(temp);
		}
	}
}
